package com.sda.huoshui.api

import android.annotation.SuppressLint
import android.content.Context
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

/**
 * Created by zly on 2018/4/18.
 */

class RetrofitHelper private constructor(private val mCntext: Context) {

    private val logInterceptor = HttpLoggingInterceptor(HttpLogger()).setLevel(HttpLoggingInterceptor.Level.BODY)
    private var client = OkHttpClient().newBuilder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(20, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .addInterceptor(logInterceptor)
//        .addInterceptor(BaseUrlInterceptor())
        .proxy(Proxy.NO_PROXY)
        .build()
    private var factory = GsonConverterFactory.create(GsonBuilder().create())
    private var mRetrofit: Retrofit? = null

    //getServer方法就是为了获取RetrofitService接口类的实例化
    val server: RetrofitService
        get() = mRetrofit!!.create(RetrofitService::class.java)

    init {
        init()
    }

    private fun init() {
        resetApp()
    }

    //resetApp方法，就是Retrofit的创建
    private fun resetApp() {
        mRetrofit = Retrofit.Builder()
            .addConverterFactory(factory)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(client)
            .baseUrl(BaseUrl.BASE_START_URL)
            .build()
    }

    companion object {
        @SuppressLint("StaticFieldLeak")
        private var instance: RetrofitHelper? = null

        fun getInstance(context: Context): RetrofitHelper {
            if (instance == null) {
                instance = RetrofitHelper(context)
            }
            return instance as RetrofitHelper
        }
    }

}
